package org.example.day08;

/**
 * 第三章节3.1.19.4: 分析假死的原因
 *      原因: 连续唤醒了同类.
 *      解决方法: 将notify修改成notifyAll.
 **/
//生产者
public class Productor {
    private String lock;

    public Productor(String lock) {
        this.lock = lock;
    }

    public void setValue() {
        try {
            synchronized (lock) {
                while (!ValueObject2.value.equals("")) {
                    System.out.println("生产者: " + Thread.currentThread().getName() + "waiting了★");
                    lock.wait();
                }
                System.out.println("生产者: " + Thread.currentThread().getName() + "Runnable了");
                String value = System.currentTimeMillis() + "_" + System.nanoTime();
                ValueObject2.value = value;
                lock.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        String lock = new String("");
        Productor productor = new Productor(lock);
        Consumer consumer = new Consumer(lock);
        ThreadP[] PThread = new ThreadP[2];
        ThreadC[] CThread = new ThreadC[2];
        for (int i = 0; i < 2; i++) {
            PThread[i] = new ThreadP(productor);
            PThread[i].setName("生产者" + (i + 1));
            CThread[i] = new ThreadC(consumer);
            CThread[i].setName("消费者" + (i + 1));
            PThread[i].start();
            CThread[i].start();
        }
        Thread.sleep(5000);
        Thread[] array = new Thread[Thread.currentThread().getThreadGroup().activeCount()];
        Thread.currentThread().getThreadGroup().enumerate(array);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i].getName() + " --- " + array[i].getState());
        }
    }
}

//消费者
class Consumer {
    private String lock;

    public Consumer(String lock) {
        this.lock = lock;
    }

    public void getValue() {
        try {
            synchronized (lock) {
                while (ValueObject2.value.equals("")) {
                    System.out.println("消费者: " + Thread.currentThread().getName() + "waiting了☆");
                    lock.wait();
                }
                System.out.println("消费者: " + Thread.currentThread().getName() + "Runnable了");
                ValueObject2.value = "";
                lock.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

//生产者线程
class ThreadP extends Thread {
    private Productor p;

    public ThreadP(Productor p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (true) {
            p.setValue();
        }
    }
}

//消费者线程
class ThreadC extends Thread {
    private Consumer c;

    public ThreadC(Consumer c) {
        this.c = c;
    }

    @Override
    public void run() {
        while (true) {
            c.getValue();
        }
    }
}

